package role

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
	"wms/internal/svc"
	"wms/internal/types"
	"wms/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddLogic {
	return &AddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddLogic) Add(req *types.RoleAddRequest) (resp *types.BaseResponse, err error) {
	resp = new(types.BaseResponse)

	uid, err := l.ctx.Value("uid").(json.Number).Int64()
	if err != nil {
		fmt.Printf("[Error]用户id解析:%s\n", err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	//1.角色名称是否重复
	name := strings.TrimSpace(req.Name)
	count, err := l.svcCtx.RoleModel.Count(l.ctx, fmt.Sprintf(" where name = '%s'", name))
	fmt.Println(count, err)
	if err != nil {
		fmt.Printf("[Error]角色[%s]查询：%s\n", name, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	if count > 0 {
		fmt.Printf("[Error]角色[%s]重复添加\n", name)
		resp.Code = http.StatusBadRequest
		resp.Msg = "角色重复添加"
		return resp, nil
	}

	//2.角色入库
	_, err = l.svcCtx.RoleModel.Insert(l.ctx, &model.Role{
		Name:      name,
		Status:    req.Status,
		SortId:    req.SortId,
		Remark:    strings.TrimSpace(req.Remark),
		CreatedBy: uid,
	})
	if err != nil {
		fmt.Printf("[Error]角色[%s]入库：%s\n", name, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	resp.Code = http.StatusOK
	resp.Msg = "成功"

	return resp, nil
}
